package org.liquidByte.trafficMustang.androidApp.listview.adapter;

import org.liquidByte.trafficMustang.R;

import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class DisplayNoDataAdapter extends BaseAdapter {
	
	private final BaseAdapter adapter;
	private final LayoutInflater inflater;
	private View emptyView;
	
	public DisplayNoDataAdapter(Context ctx, BaseAdapter wrappedAdapter) {
		if (wrappedAdapter == null) {
			throw new IllegalArgumentException("wrappedAdapter is null");
		}
		if (ctx == null) {
			throw new IllegalArgumentException("ctx is null");
		}
		this.adapter = wrappedAdapter;
		this.inflater = LayoutInflater.from(ctx);
		wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
			@Override
			public void onChanged() {
				super.onChanged();
				DisplayNoDataAdapter.this.notifyDataSetChanged();
			}
			@Override
			public void onInvalidated() {
				super.onInvalidated();
				DisplayNoDataAdapter.this.notifyDataSetInvalidated();
			}
		});
	}

	public boolean isEmpty() {
		return this.adapter.getCount() == 0;
	}
	
	protected View getEmptyView() {
		if (this.emptyView == null) {
			this.emptyView = this.inflater.inflate(R.layout.listview_row_empty, null);
		}
		return emptyView;
	}

	@Override
	public int getCount() {
		if (this.isEmpty()) {
			return 1;
		} else {
			return this.adapter.getCount();
		}
	}

	@Override
	public Object getItem(int position) {
		if (this.isEmpty()) {
			return new Object();
		} else {
			return this.adapter.getItem(position);
		}
	}

	@Override
	public long getItemId(int position) {
		if (this.isEmpty()) {
			return 0;
		} else {
			return this.adapter.getItemId(position);
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (this.isEmpty()) {
			return this.getEmptyView();
		} else {
			return this.adapter.getView(position, convertView, parent);
		}
	}
	
}
